<template>
  <div class="outsourcing-show">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>委外加工管理</h2>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
        <el-form-item label="生产单号" prop="productionOrderNumber">
          <el-input v-model="queryParams.productionOrderNumber" placeholder="请输入生产单号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="生产主题" prop="productionTheme">
          <el-input v-model="queryParams.productionTheme" placeholder="请输入生产主题" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="委托单位" prop="entrustingUnit">
          <el-select v-model="queryParams.entrustingUnit" placeholder="请选择委托单位" clearable filterable
            style="width: 200px">
            <el-option v-for="supplier in supplierOptions" :key="supplier.id" :label="supplier.supplierName"
              :value="supplier.supplierName" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="queryParams.contactPerson" placeholder="请输入联系人" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px">
            <el-option label="未完成" value="未完成" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已确认" value="已确认" />
            <el-option label="生产中" value="生产中" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围" prop="dateRange">
          <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="handleDateRangeChange"
            style="width: 300px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="operation-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAdd" :icon="Plus">
            新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" @click="handleExport" :icon="Download">
            导出
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column prop="productionOrderNumber" label="生产单号" width="180" />
        <el-table-column prop="productionTheme" label="生产主题" width="200" />
        <el-table-column prop="documentDate" label="单据日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.documentDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="entrustingUnit" label="委托单位" width="150" />
        <el-table-column prop="contactPerson" label="联系人" width="100" />
        <el-table-column prop="responsiblePerson" label="负责人" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="物品概要" width="200">
          <template #default="scope">
            <div class="item-summary-container">
              <span class="item-summary-text">{{ scope.row.itemSummary || '暂无物品' }}</span>
              <div class="item-summary-buttons">
                <el-button 
                  v-if="scope.row.productionItems && scope.row.productionItems.length > 0"
                  size="small" 
                  type="primary" 
                  @click="showProductionItems(scope.row)"
                >
                  生产物品 ({{ scope.row.productionItems.length }}项)
                </el-button>
                <el-button 
                  v-if="scope.row.consumeItems && scope.row.consumeItems.length > 0"
                  size="small" 
                  type="success" 
                  @click="showConsumeItems(scope.row)"
                >
                  消耗物品 ({{ scope.row.consumeItems.length }}项)
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" style="width: 50px;" type="primary" @click="handleEdit(scope.row)" :icon="Edit">
              编辑
            </el-button>
            <el-button size="small" style="width: 50px;" type="danger" @click="handleDelete(scope.row)" :icon="Delete">
              删除
            </el-button>
            <el-button size="small" style="width: 50px;" type="info" @click="handleView(scope.row)" :icon="View">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination v-model:current-page="queryParams.pageIndex" v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%" :before-close="handleDialogClose">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产单号" prop="productionOrderNumber">
              <el-input v-model="formData.productionOrderNumber" placeholder="请输入生产单号" :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产主题" prop="productionTheme">
              <el-input v-model="formData.productionTheme" placeholder="请输入生产主题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单据日期" prop="documentDate">
              <el-date-picker v-model="formData.documentDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产类型" prop="productionType">
              <el-select v-model="formData.productionType" placeholder="请选择生产类型" style="width: 100%">
                <el-option label="委外加工" value="委外加工" />
                <el-option label="内部生产" value="内部生产" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联项目" prop="relatedProject">
              <el-select v-model="formData.relatedProject" placeholder="请选择关联项目" filterable style="width: 100%">
                <el-option v-for="project in projectOptions" :key="project.id"
                  :label="`${project.projectName} (${project.projectNumber})`" :value="project.projectName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在部门" prop="department">
              <el-select v-model="formData.department" placeholder="请选择所在部门" filterable style="width: 100%">
                <el-option v-for="department in departmentOptions" :key="department.id"
                  :label="department.departmentName" :value="department.departmentName" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="委托单位" prop="entrustingUnit">
              <el-select v-model="formData.entrustingUnit" placeholder="请选择委托单位" filterable style="width: 100%">
                <el-option v-for="supplier in supplierOptions" :key="supplier.id" :label="supplier.supplierName"
                  :value="supplier.supplierName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="responsiblePerson">
              <el-input v-model="formData.responsiblePerson" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销售订单" prop="salesOrderId">
              <el-input v-model="formData.salesOrderNumber" placeholder="请选择销售订单" readonly
                @click="openSalesOrderDialog">
                <template #append>
                  <el-button @click="openSalesOrderDialog">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="未完成" value="未完成" />
                <el-option label="已完成" value="已完成" />
                <el-option label="已确认" value="已确认" />
                <el-option label="生产中" value="生产中" />
                <el-option label="已取消" value="已取消" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="formData.remarks" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>

        <!-- 生产物品表格 -->
        <el-form-item label="生产物品">
          <div class="table-header">
            <el-button type="primary" size="small" @click="openProductionItemDialog">
              添加生产物品
            </el-button>
          </div>
          <el-table :data="formData.productionItems" style="width: 100%">
            <el-table-column prop="itemCode" label="物品编码" width="120" />
            <el-table-column prop="itemName" label="物品名称" width="150" />
            <el-table-column prop="specification" label="规格" width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="itemType" label="物品类型" width="100" />
            <el-table-column prop="brand" label="品牌" width="100" />
            <el-table-column prop="inventory" label="库存" width="80" />
            <el-table-column prop="purchasePrice" label="采购价" width="100" />
            <el-table-column prop="salePrice" label="销售价" width="100" />
            <el-table-column prop="manufacturerModel" label="制造商型号" width="120" />
            <el-table-column label="计划数量" width="120">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.plannedQuantity" 
                  :min="1" 
                  :precision="2"
                  size="small"
                  style="width: 100px"
                  placeholder="数量"
                />
              </template>
            </el-table-column>
            <el-table-column label="备注" width="150">
              <template #default="scope">
                <el-input 
                  v-model="scope.row.remark" 
                  size="small"
                  placeholder="备注"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button size="small" type="danger" @click="removeProductionItem(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <!-- 消耗物品表格 -->
        <el-form-item label="消耗物品">
          <div class="table-header">
            <el-button type="primary" size="small" @click="openConsumeItemDialog">
              添加消耗物品
            </el-button>
          </div>
          <el-table :data="formData.consumeItems" style="width: 100%">
            <el-table-column prop="itemCode" label="物品编码" width="120" />
            <el-table-column prop="itemName" label="物品名称" width="150" />
            <el-table-column prop="specification" label="规格" width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="itemType" label="物品类型" width="100" />
            <el-table-column prop="brand" label="品牌" width="100" />
            <el-table-column prop="inventory" label="库存" width="80" />
            <el-table-column prop="purchasePrice" label="采购价" width="100" />
            <el-table-column prop="salePrice" label="销售价" width="100" />
            <el-table-column prop="manufacturerModel" label="制造商型号" width="120" />
            <el-table-column label="仓库" width="150">
              <template #default="scope">
                <el-select 
                  v-model="scope.row.warehouseId" 
                  size="small"
                  placeholder="请选择仓库"
                  style="width: 100%"
                >
                  <el-option 
                    v-for="warehouse in warehouseOptions" 
                    :key="warehouse.id" 
                    :label="warehouse.warehouseName" 
                    :value="warehouse.warehouseName"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="计划数量" width="120">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.plannedQuantity" 
                  :min="1" 
                  :precision="2"
                  size="small"
                  style="width: 100px"
                  placeholder="数量"
                />
              </template>
            </el-table-column>
            <el-table-column label="实际数量" width="120">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.number" 
                  :min="1" 
                  :precision="2"
                  size="small"
                  style="width: 100px"
                  placeholder="数量"
                />
              </template>
            </el-table-column>
            <el-table-column label="备注" width="150">
              <template #default="scope">
                <el-input 
                  v-model="scope.row.remark" 
                  size="small"
                  placeholder="备注"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button size="small" type="danger" @click="removeConsumeItem(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <!-- 附件管理 -->
        <el-form-item label="附件">
          <div class="attachment-container">
            <div class="existing-attachments" v-if="formData.attachments && formData.attachments.length > 0">
              <div v-for="(attachment, index) in formData.attachments" :key="index" class="attachment-item">
                <div class="attachment-info">
                  <div class="file-name">{{ attachment.fileName }}</div>
                  <div class="file-size">文件大小: {{ attachment.fileSize }}</div>
                  <div class="upload-date">上传日期: {{ attachment.uploadDate }}</div>
                </div>
                <div class="attachment-actions">
                  <el-button type="text" @click="handleViewAttachment(attachment)">查看</el-button>
                  <el-button type="text" @click="handleDeleteAttachment(attachment, index)">删除</el-button>
                </div>
              </div>
            </div>

            <div class="upload-area">
              <el-upload ref="uploadRef" :action="uploadUrl" :headers="uploadHeaders" :on-success="handleUploadSuccess"
                :on-error="handleUploadError" :before-upload="beforeUpload" :show-file-list="false" :multiple="true"
                :limit="10" drag
                accept=".jpg,.jpeg,.png,.gif,.bmp,.webp,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv,.zip,.rar">
                <el-icon class="el-icon--upload">
                  <UploadFilled />
                </el-icon>
                <div class="el-upload__text">
                  <p>点击上传 / 拖拽文件到此区域</p>
                  <p class="upload-tip">支持格式：图片、Word、Excel、PDF、CSV、压缩包等，单个文件最大50MB</p>
                </div>
              </el-upload>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 销售订单选择对话框 -->
    <el-dialog v-model="salesOrderDialogVisible" title="选择销售订单" width="80%">
      <el-form :inline="true" :model="salesOrderQuery" class="search-form">
        <el-form-item label="搜索">
          <el-input v-model="salesOrderQuery.searchText" placeholder="销售单号/主题/客户名称" style="width: 200px" />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="salesOrderQuery.customerName" placeholder="请输入客户名称" style="width: 200px" />
        </el-form-item>
        <el-form-item label="销售日期">
          <el-date-picker v-model="salesOrderQuery.salesDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" style="width: 200px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="salesOrderQuery.purchaseStatus" placeholder="请选择状态" style="width: 200px">
            <el-option label="全部" value="" />
            <el-option label="已确认" value="已确认" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSalesOrders">搜索</el-button>
          <el-button @click="resetSalesOrderQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="salesOrderLoading" :data="salesOrderData" @row-click="selectSalesOrder" style="width: 100%">
        <el-table-column prop="salesOrderNumber" label="销售单号" width="180" />
        <el-table-column prop="salesOrderSubject" label="销售主题" width="200" />
        <el-table-column prop="customerName" label="客户名称" width="150" />
        <el-table-column prop="salesDate" label="销售日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.salesDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="purchaseStatus" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.purchaseStatus)">
              {{ scope.row.purchaseStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="itemSummary" label="物品概要" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button size="small" type="primary" @click="selectSalesOrder(scope.row)">
              选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination v-model:current-page="salesOrderQuery.pageIndex" v-model:page-size="salesOrderQuery.pageSize"
        :page-sizes="[10, 20, 50]" :total="salesOrderTotal" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSalesOrderSizeChange" @current-change="handleSalesOrderCurrentChange"
        style="margin-top: 20px; text-align: right" />
    </el-dialog>

    <!-- 生产物品选择对话框 -->
    <el-dialog v-model="productionItemDialogVisible" title="选择生产物品" width="80%">
      <el-form :inline="true" :model="itemQuery" class="search-form">
        <el-form-item label="搜索">
          <el-input v-model="itemQuery.searchText" placeholder="物品编码/名称/规格" style="width: 200px" />
        </el-form-item>
        <el-form-item label="物品类型">
          <el-select v-model="itemQuery.itemType" placeholder="请选择类型" style="width: 200px">
            <el-option label="全部" value="" />
            <el-option label="原材料" value="原材料" />
            <el-option label="半成品" value="半成品" />
            <el-option label="成品" value="成品" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存状态">
          <el-select v-model="itemQuery.inventoryStatus" placeholder="请选择状态" style="width: 200px">
            <el-option label="全部" value="" />
            <el-option label="有库存" value="有库存" />
            <el-option label="无库存" value="无库存" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchProductionItems">搜索</el-button>
          <el-button @click="resetItemQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="itemLoading" :data="itemData" @selection-change="handleItemSelectionChange"
        style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="itemCode" label="物品编码" width="120" />
        <el-table-column prop="itemName" label="物品名称" width="150" />
        <el-table-column prop="specification" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="itemType" label="类型" width="100" />
        <el-table-column prop="inventory" label="库存" width="80" />
      </el-table>

      <el-pagination v-model:current-page="itemQuery.pageIndex" v-model:page-size="itemQuery.pageSize"
        :page-sizes="[10, 20, 50]" :total="itemTotal" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleItemSizeChange" @current-change="handleItemCurrentChange"
        style="margin-top: 20px; text-align: right" />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="productionItemDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmProductionItems">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 消耗物品选择对话框 -->
    <el-dialog v-model="consumeItemDialogVisible" title="选择消耗物品" width="80%">
      <el-form :inline="true" :model="itemQuery" class="search-form">
        <el-form-item label="搜索">
          <el-input v-model="itemQuery.searchText" placeholder="物品编码/名称/规格" style="width: 200px" />
        </el-form-item>
        <el-form-item label="物品类型">
          <el-select v-model="itemQuery.itemType" placeholder="请选择类型" style="width: 200px">
            <el-option label="全部" value="" />
            <el-option label="原材料" value="原材料" />
            <el-option label="半成品" value="半成品" />
            <el-option label="成品" value="成品" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存状态">
          <el-select v-model="itemQuery.inventoryStatus" placeholder="请选择状态" style="width: 200px">
            <el-option label="全部" value="" />
            <el-option label="有库存" value="有库存" />
            <el-option label="无库存" value="无库存" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchConsumeItems">搜索</el-button>
          <el-button @click="resetItemQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="itemLoading" :data="itemData" @selection-change="handleItemSelectionChange"
        style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="itemCode" label="物品编码" width="120" />
        <el-table-column prop="itemName" label="物品名称" width="150" />
        <el-table-column prop="specification" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="itemType" label="类型" width="100" />
        <el-table-column prop="inventory" label="库存" width="80" />
      </el-table>

      <el-pagination v-model:current-page="itemQuery.pageIndex" v-model:page-size="itemQuery.pageSize"
        :page-sizes="[10, 20, 50]" :total="itemTotal" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleItemSizeChange" @current-change="handleItemCurrentChange"
        style="margin-top: 20px; text-align: right" />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="consumeItemDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmConsumeItems">确定</el-button>
        </span>
      </template>
    </el-dialog>



    <!-- 详情查看对话框 -->
    <el-dialog v-model="detailVisible" title="委外加工详情" width="80%">
      <div v-if="currentDetailRecord">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="生产单号">
            {{ currentDetailRecord.productionOrderNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="生产主题">
            {{ currentDetailRecord.productionTheme }}
          </el-descriptions-item>
          <el-descriptions-item label="单据日期">
            {{ formatDate(currentDetailRecord.documentDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="生产类型">
            {{ currentDetailRecord.productionType }}
          </el-descriptions-item>
          <el-descriptions-item label="委托单位">
            {{ currentDetailRecord.entrustingUnit }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ currentDetailRecord.contactPhone }}
          </el-descriptions-item>
          <el-descriptions-item label="联系人">
            {{ currentDetailRecord.contactPerson }}
          </el-descriptions-item>
          <el-descriptions-item label="负责人">
            {{ currentDetailRecord.responsiblePerson }}
          </el-descriptions-item>
          <el-descriptions-item label="销售订单">
            {{ currentDetailRecord.salesOrderNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentDetailRecord.status)">
              {{ currentDetailRecord.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ currentDetailRecord.remarks }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">生产物品</el-divider>
        <el-table :data="currentDetailRecord.productionItems || []" style="width: 100%">
          <el-table-column prop="itemCode" label="物品编码" width="120" />
          <el-table-column prop="itemName" label="物品名称" width="150" />
          <el-table-column prop="specification" label="规格" width="120" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="itemType" label="物品类型" width="100" />
          <el-table-column prop="brand" label="品牌" width="100" />
          <el-table-column prop="inventory" label="库存" width="80" />
          <el-table-column prop="purchasePrice" label="采购价" width="100" />
          <el-table-column prop="salePrice" label="销售价" width="100" />
          <el-table-column prop="manufacturerModel" label="制造商型号" width="120" />
          <el-table-column prop="plannedQuantity" label="计划数量" width="100" />
          <el-table-column prop="remark" label="备注" width="150" />
        </el-table>

        <el-divider content-position="left">消耗物品</el-divider>
        <el-table :data="currentDetailRecord.consumeItems || []" style="width: 100%">
          <el-table-column prop="itemCode" label="物品编码" width="120" />
          <el-table-column prop="itemName" label="物品名称" width="150" />
          <el-table-column prop="specification" label="规格" width="120" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="itemType" label="物品类型" width="100" />
          <el-table-column prop="brand" label="品牌" width="100" />
          <el-table-column prop="inventory" label="库存" width="80" />
          <el-table-column prop="purchasePrice" label="采购价" width="100" />
          <el-table-column prop="salePrice" label="销售价" width="100" />
          <el-table-column prop="manufacturerModel" label="制造商型号" width="120" />
          <el-table-column prop="warehouseId" label="仓库" width="100" />
          <el-table-column prop="plannedQuantity" label="计划数量" width="100" />
          <el-table-column prop="number" label="实际数量" width="100" />
          <el-table-column prop="remark" label="备注" width="150" />
        </el-table>

        <el-divider content-position="left">附件</el-divider>
        <div class="attachment-list"
          v-if="currentDetailRecord.attachments && currentDetailRecord.attachments.length > 0">
          <div class="attachment-item" v-for="attachment in currentDetailRecord.attachments" :key="attachment.id">
            <div class="attachment-info">
              <div class="file-name">{{ attachment.fileName }}</div>
              <div class="file-details">
                <span class="file-size">文件大小: {{ attachment.fileSizeText || formatFileSize(attachment.fileSize)
                  }}</span>
                <span class="upload-date">上传日期: {{ formatDate(attachment.uploadDate) }}</span>
              </div>
            </div>
            <div class="attachment-actions">
              <el-button size="small" type="primary" @click="viewAttachment(attachment)">
                查看
              </el-button>
              <el-button size="small" type="success" @click="downloadAttachment(attachment)">
                下载
              </el-button>
            </div>
          </div>
        </div>
        <el-empty v-else description="暂无附件" :image-size="60" />
      </div>
    </el-dialog>

    <!-- 生产物品列表查看对话框 -->
    <el-dialog v-model="productionItemsDialogVisible" title="生产物品列表" width="80%">
      <el-table :data="currentProductionItems" style="width: 100%">
        <el-table-column prop="itemCode" label="物品编码" width="120" />
        <el-table-column prop="itemName" label="物品名称" width="150" />
        <el-table-column prop="specification" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="itemType" label="物品类型" width="100" />
        <el-table-column prop="brand" label="品牌" width="100" />
        <el-table-column prop="inventory" label="库存" width="80" />
        <el-table-column prop="purchasePrice" label="采购价" width="100" />
        <el-table-column prop="salePrice" label="销售价" width="100" />
        <el-table-column prop="manufacturerModel" label="制造商型号" width="120" />
        <el-table-column prop="plannedQuantity" label="计划数量" width="100" />
        <el-table-column prop="remark" label="备注" width="150" />
      </el-table>
    </el-dialog>

    <!-- 消耗物品列表查看对话框 -->
    <el-dialog v-model="consumeItemsDialogVisible" title="消耗物品列表" width="80%">
      <el-table :data="currentConsumeItems" style="width: 100%">
        <el-table-column prop="itemCode" label="物品编码" width="120" />
        <el-table-column prop="itemName" label="物品名称" width="150" />
        <el-table-column prop="specification" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="itemType" label="物品类型" width="100" />
        <el-table-column prop="brand" label="品牌" width="100" />
        <el-table-column prop="inventory" label="库存" width="80" />
        <el-table-column prop="purchasePrice" label="采购价" width="100" />
        <el-table-column prop="salePrice" label="销售价" width="100" />
        <el-table-column prop="manufacturerModel" label="制造商型号" width="120" />
        <el-table-column prop="warehouseId" label="仓库" width="100" />
        <el-table-column prop="plannedQuantity" label="计划数量" width="100" />
        <el-table-column prop="number" label="实际数量" width="100" />
        <el-table-column prop="remark" label="备注" width="150" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Download, Edit, Delete, View, UploadFilled, ArrowDown } from '@element-plus/icons-vue'
import {
  getOutsourcingList,
  getOutsourcingById,
  addOutsourcing,
  updateOutsourcing,
  deleteOutsourcing,
  getSalesOrders,
  getItemsBySalesOrder,
  getAllItems,
  updateOutsourcingStatus,
  getSuppliers,
  getProjects,
  GetAllDepartments,
  GetAttachmentsByEntityId,
  AddAttachments,
  DeleteAttachment,
  getWarehouses
} from '@/Https/server'
import * as XLSX from 'xlsx'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const dateRange:any = ref([])
const selectedRows:any = ref([])

// 供应商相关数据
const supplierOptions:any = ref([])
const supplierLoading = ref(false)

// 项目相关数据
const projectOptions:any = ref([])
const projectLoading:any = ref(false)

// 部门相关数据
const departmentOptions:any = ref([])
const departmentLoading = ref(false)

// 仓库相关数据
const warehouseOptions:any = ref([])
const warehouseLoading:any = ref(false)

// 查询参数
const queryParams:any = reactive({
  pageIndex: 1,
  pageSize: 10,
  productionOrderNumber: '',
  productionTheme: '',
  entrustingUnit: '',
  contactPerson: '',
  status: '',
  startDate: '',
  endDate: ''
})

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const formRef = ref()
const formData:any = reactive({
  id: 0,
  productionOrderNumber: '',
  productionTheme: '',
  documentDate: '',
  productionType: '委外加工',
  relatedProject: '',
  department: '',
  entrustingUnit: '',
  contactPhone: '',
  contactPerson: '',
  responsiblePerson: '',
  salesOrderId: null,
  salesOrderNumber: '',
  remarks: '',
  status: '未完成',
  productionItems: [],
  consumeItems: [],
  attachments: []
})

// 表单验证规则
const formRules = {
  productionOrderNumber: [
    { required: true, message: '请输入生产单号', trigger: 'blur' }
  ],
  productionTheme: [
    { required: true, message: '请输入生产主题', trigger: 'blur' }
  ],
  documentDate: [
    { required: true, message: '请选择单据日期', trigger: 'change' }
  ],
  entrustingUnit: [
    { required: true, message: '请输入委托单位', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ]
}

// 销售订单对话框
const salesOrderDialogVisible = ref(false)
const salesOrderLoading = ref(false)
const salesOrderData = ref([])
const salesOrderTotal = ref(0)
const salesOrderQuery:any = reactive({
  pageIndex: 1,
  pageSize: 10,
  searchText: '',
  customerName: '',
  salesDate: '',
  purchaseStatus: ''
})

// 物品选择对话框
const productionItemDialogVisible = ref(false)
const consumeItemDialogVisible = ref(false)
const itemLoading = ref(false)
const itemData = ref([])
const itemTotal = ref(0)
const selectedItems = ref([])
const itemQuery:any = reactive({
  pageIndex: 1,
  pageSize: 10,
  searchText: '',
  itemType: '',
  itemClassificationId: null,
  inventoryStatus: ''
})

// 详情对话框
const detailVisible:any = ref(false)
const currentDetailRecord:any = ref(null)

// 物品列表查看对话框
const productionItemsDialogVisible = ref(false)
const consumeItemsDialogVisible = ref(false)
const currentProductionItems = ref([])
const currentConsumeItems = ref([])

// 附件相关
const uploadRef = ref()
const uploadUrl = import.meta.env.VITE_UploadAPP_API_URL + 'api/FileUpload/UploadFile'
const uploadHeaders = {
  'Authorization': 'Bearer ' + localStorage.getItem('token') || ''
}

// 显示生产物品列表
const showProductionItems = (row:any) => {
  currentProductionItems.value = row.productionItems || []
  productionItemsDialogVisible.value = true
}

// 显示消耗物品列表
const showConsumeItems = (row:any) => {
  currentConsumeItems.value = row.consumeItems || []
  consumeItemsDialogVisible.value = true
}

// 方法
const formatDate = (date:any) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

const getStatusType = (status:any) => {
  const statusMap:any = {
    '未完成': 'warning',
    '已完成': 'success',
    '已确认': 'primary',
    '生产中': 'info',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取列表数据
const fetchList = async () => {
  loading.value = true
  try {
    const response:any = await getOutsourcingList(queryParams)
    if (response.code === 200) {
      console.log('列表数据:', response.data.pageData)
      tableData.value = response.data.pageData
      total.value = response.data.totalCount
      
      // 检查物品概要数据
      response.data.pageData.forEach((item:any, index:any) => {
        console.log(`第${index + 1}条记录 - ID: ${item.id}, 物品概要: ${item.itemSummary}`)
      })
    } else {
      ElMessage.error(response.message || '获取列表失败')
    }
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}
// 获取供应商列表
const fetchSuppliers = async () => {
  supplierLoading.value = true
  try {
    const response:any = await getSuppliers({
      pageIndex: 1,
      pageSize: 1000, // 获取所有供应商
      searchText: '', // 使用空格而不是空字符串
      supplierType: '', // 使用空格而不是空字符串
      supplierStatus: 'Active' // 只获取活跃状态的供应商
    })
    console.log(response)
    if (response.code === 200) {

      supplierOptions.value = response.data.pageData
    } else {
      ElMessage.error(response.message || '获取供应商列表失败')
    }
  } catch (error) {
    console.error('获取供应商列表失败:', error)
    ElMessage.error('获取供应商列表失败')
  } finally {
    supplierLoading.value = false
  }
}

// 获取项目列表
const fetchProjects = async () => {
  projectLoading.value = true
  try {
    const response:any = await getProjects({
      pageIndex: 1,
      pageSize: 1000, // 获取所有项目
      searchText: ' ', // 使用空格而不是空字符串
      projectStatus: ' ', // 使用空格而不是空字符串
      category: ' ' // 使用空格而不是空字符串
    })
    if (response.code === 200) {
      projectOptions.value = response.data.pageData
    } else {
      ElMessage.error(response.message || '获取项目列表失败')
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  } finally {
    projectLoading.value = false
  }
}

// 获取部门列表
const fetchDepartments = async () => {
  departmentLoading.value = true
  try {
    const response:any = await GetAllDepartments()
    if (response.code === 200) {
      departmentOptions.value = response.data
    } else {
      ElMessage.error(response.message || '获取部门列表失败')
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  } finally {
    departmentLoading.value = false
  }
}

// 获取仓库列表
const fetchWarehouses = async () => {
  warehouseLoading.value = true
  try {
    const response:any = await getWarehouses()
    if (response.code === 200) {
      warehouseOptions.value = response.data
    } else {
      ElMessage.error(response.message || '获取仓库列表失败')
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  } finally {
    warehouseLoading.value = false
  }
}

// 查询相关方法
const handleDateRangeChange = (val:any) => {
  if (val) {
    queryParams.startDate = val[0]
    queryParams.endDate = val[1]
  } else {
    queryParams.startDate = ''
    queryParams.endDate = ''
  }
}

const handleQuery = () => {
  queryParams.pageIndex = 1
  fetchList()
}

const handleReset = () => {
  Object.assign(queryParams, {
    pageIndex: 1,
    pageSize: 10,
    productionOrderNumber: '',
    productionTheme: '',
    entrustingUnit: '',
    contactPerson: '',
    status: '',
    startDate: '',
    endDate: ''
  })
  dateRange.value = []
  fetchList()
}

const handleSizeChange = (size:any) => {
  queryParams.pageSize = size
  queryParams.pageIndex = 1
  fetchList()
}

const handleCurrentChange = (page:any) => {
  queryParams.pageIndex = page
  fetchList()
}

const handleSelectionChange = (selection:any) => {
  selectedRows.value = selection
}

// 新增/编辑相关方法
const handleAdd = () => {
  dialogTitle.value = '新增委外加工'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = async (row:any) => {
  try {
    const response:any = await getOutsourcingById({ id: row.id })
    if (response.code === 200) {
      dialogTitle.value = '编辑委外加工'
      isEdit.value = true
      Object.assign(formData, {
        ...response.data,
        attachments: [] // 先清空附件列表
      })

      // 直接使用后端返回的数据，已经包含了完整的物品信息
      formData.productionItems = response.data.productionItems || []
      formData.consumeItems = response.data.consumeItems || []

      // 加载附件列表
      try {
        const attachmentResponse:any = await GetAttachmentsByEntityId({
          entityId: row.id,
          entityType: 'OutsourcingProcessing'
        })
        if (attachmentResponse.code === 200) {
          formData.attachments = attachmentResponse.data.map((attachment:any) => ({
            fileName: attachment.filename,
            fileSize: formatFileSize(attachment.filesize),
            uploadDate: new Date(attachment.uploadtime).toLocaleString(),
            fileUrl: attachment.filepath,
            filePath: attachment.filepath,
            originalFileName: attachment.filename,
            fileSizeBytes: attachment.filesize,
            fileType: attachment.filename.substring(attachment.filename.lastIndexOf('.')).toLowerCase(),
            fileExtension: attachment.filename.substring(attachment.filename.lastIndexOf('.')).toLowerCase(),
            id: attachment.id // 添加附件ID，用于删除操作
          }))
        }
      } catch (attachmentError) {
        console.error('加载附件失败:', attachmentError)
        formData.attachments = []
      }

      dialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

const handleDelete = async (row:any) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response:any = await deleteOutsourcing({ id: row.id })
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleView = async (row:any) => {
  try {
    console.log('查看详情，委外加工ID:', row.id)
    const response:any = await getOutsourcingById({ id: row.id })
    if (response.code === 200) {
      console.log('详情数据:', response.data)
      currentDetailRecord.value = response.data
      
      // 加载附件列表
      try {
        const attachmentResponse:any = await GetAttachmentsByEntityId({
          entityId: row.id,
          entityType: 'OutsourcingProcessing'
        })
        if (attachmentResponse.code === 200) {
          currentDetailRecord.value.attachments = attachmentResponse.data.map((attachment:any) => ({
            fileName: attachment.filename,
            fileSize: attachment.filesize,
            fileSizeText: formatFileSize(attachment.filesize),
            uploadDate: attachment.uploadtime,
            fileUrl: attachment.filepath,
            filePath: attachment.filepath,
            id: attachment.id
          }))
        } else {
          currentDetailRecord.value.attachments = []
        }
      } catch (attachmentError) {
        console.error('加载附件失败:', attachmentError)
        currentDetailRecord.value.attachments = []
      }
      
      detailVisible.value = true
    } else {
      ElMessage.error(response.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

const handleExport = async () => {
  try {
    // 获取所有数据（不分页）
    const exportParams = { ...queryParams, pageSize: 999999, pageIndex: 1 }
    const response: any = await getOutsourcingList(exportParams)
    
    if (response.code === 200) {
      const data = response.data.pageData || []
      
      // 准备导出数据
      const exportData = data.map((item: any, index: number) => ({
        '序号': index + 1,
        '生产单号': item.productionOrderNumber || '',
        '生产主题': item.productionTheme || '',
        '单据日期': item.documentDate ? new Date(item.documentDate).toLocaleDateString() : '',
        '委托单位': item.entrustingUnit || '',
        '联系人': item.contactPerson || '',
        '负责人': item.responsiblePerson || '',
        '状态': item.status || '',
        '物品概要': item.itemSummary || '',
        '备注': item.remarks || '',
        '创建时间': item.createTime ? new Date(item.createTime).toLocaleString() : ''
      }))
      
      // 创建工作簿
      const wb = XLSX.utils.book_new()
      const ws = XLSX.utils.json_to_sheet(exportData)
      
      // 设置列宽
      const colWidths = [
        { wch: 6 },  // 序号
        { wch: 15 }, // 生产单号
        { wch: 20 }, // 生产主题
        { wch: 12 }, // 单据日期
        { wch: 15 }, // 委托单位
        { wch: 10 }, // 联系人
        { wch: 10 }, // 负责人
        { wch: 8 },  // 状态
        { wch: 25 }, // 物品概要
        { wch: 20 }, // 备注
        { wch: 20 }  // 创建时间
      ]
      ws['!cols'] = colWidths
      
      XLSX.utils.book_append_sheet(wb, ws, '委外加工数据')
      
      // 下载文件
      const fileName = `委外加工数据_${new Date().toLocaleDateString().replace(/\//g, '-')}.xlsx`
      XLSX.writeFile(wb, fileName)
      
      ElMessage.success(`导出成功，共导出 ${exportData.length} 条数据`)
    } else {
      ElMessage.error(response.message || '获取导出数据失败')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    productionOrderNumber: '',
    productionTheme: '',
    documentDate: '',
    productionType: '委外加工',
    relatedProject: '',
    department: '',
    entrustingUnit: '',
    contactPhone: '',
    contactPerson: '',
    responsiblePerson: '',
    salesOrderId: null,
    salesOrderNumber: '',
    remarks: '',
    status: '未完成',
    productionItems: [],
    consumeItems: [],
    attachments: []
  })
}

const handleSubmit = async () => {
  try {
    console.log('开始提交表单...')
    console.log('表单数据:', formData)
    
    await formRef.value.validate()
    console.log('表单验证通过')

    // 构建符合新DTO结构的提交数据
    const submitData = {
      id: formData.id || 0,
      productionOrderNumber: formData.productionOrderNumber,
      productionTheme: formData.productionTheme,
      documentDate: formData.documentDate,
      productionType: formData.productionType,
      relatedProject: formData.relatedProject,
      department: formData.department,
      entrustingUnit: formData.entrustingUnit,
      contactPhone: formData.contactPhone,
      contactPerson: formData.contactPerson,
      responsiblePerson: formData.responsiblePerson,
      salesOrderId: formData.salesOrderId,
      salesOrderNumber: formData.salesOrderNumber,
      salesOrderSubject: formData.salesOrderSubject || '',
      remarks: formData.remarks,
      status: formData.status,
      createTime: formData.createTime || new Date().toISOString(),
      updateTime: formData.updateTime,
      updateName: formData.updateName,
      // 使用简化的DTO结构 - 注意属性名称大小写
      productionItems: formData.productionItems.map(item => ({
        ItemId: item.itemId,
        PlannedQuantity: item.plannedQuantity,
        Remark: item.remark || ''
      })),
      consumeItems: formData.consumeItems.map(item => ({
        ItemId: item.itemId,
        WarehouseId: item.warehouseId || '',
        PlannedQuantity: item.plannedQuantity,
        Number: item.number,
        Remark: item.remark || ''
      })),
      attachments: formData.attachments.map(attachment => ({
        Id: attachment.id || 0,
        FileName: attachment.fileName,
        OriginalFileName: attachment.originalFileName,
        FileSize: attachment.fileSizeBytes,
        FileSizeText: attachment.fileSize,
        FileType: attachment.fileType,
        FileExtension: attachment.fileExtension,
        FileUrl: attachment.fileUrl,
        FilePath: attachment.filePath,
        UploadDate: attachment.uploadDate,
        UploadBy: 'Admin',
        EntityType: 'OutsourcingProcessing',
        EntityId: formData.id || 0,
        Description: attachment.description || ''
      }))
    }

    console.log('提交数据:', submitData)
    
    let response

    if (submitData.id > 0) {
      console.log('执行更新操作...')
      response = await updateOutsourcing(submitData)
    } else {
      console.log('执行新增操作...')
      response = await addOutsourcing(submitData)
    }
    
    console.log('API响应:', response)

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
      dialogVisible.value = false
      fetchList()
    } else {
      ElMessage.error(response.message || (isEdit.value ? '更新失败' : '新增失败'))
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 销售订单选择相关方法
const openSalesOrderDialog = () => {
  salesOrderDialogVisible.value = true
  searchSalesOrders()
}

const searchSalesOrders = async () => {
  salesOrderLoading.value = true
  try {
    const response = await getSalesOrders(salesOrderQuery)
    if (response.code === 200) {
      salesOrderData.value = response.data.pageData
      salesOrderTotal.value = response.data.totalCount
    } else {
      ElMessage.error(response.message || '获取销售订单失败')
    }
  } catch (error) {
    console.error('获取销售订单失败:', error)
    ElMessage.error('获取销售订单失败')
  } finally {
    salesOrderLoading.value = false
  }
}

const resetSalesOrderQuery = () => {
  Object.assign(salesOrderQuery, {
    pageIndex: 1,
    pageSize: 10,
    searchText: '',
    customerName: '',
    salesDate: '',
    purchaseStatus: ''
  })
  searchSalesOrders()
}

const handleSalesOrderSizeChange = (size) => {
  salesOrderQuery.pageSize = size
  salesOrderQuery.pageIndex = 1
  searchSalesOrders()
}

const handleSalesOrderCurrentChange = (page) => {
  salesOrderQuery.pageIndex = page
  searchSalesOrders()
}

const selectSalesOrder = (row) => {
  console.log(row.id)
  formData.salesOrderId = row.id
  formData.salesOrderNumber = row.salesOrderNumber
  salesOrderDialogVisible.value = false
}

// 物品选择相关方法
const openProductionItemDialog = () => {
  if (!formData.salesOrderId) {
    ElMessage.warning('请先选择销售订单')
    return
  }
  productionItemDialogVisible.value = true
  searchProductionItems()
}

const openConsumeItemDialog = () => {
  consumeItemDialogVisible.value = true
  searchConsumeItems()
}

const searchProductionItems = async () => {
  itemLoading.value = true
  try {
    console.log(formData.salesOrderId);
    const response = await getItemsBySalesOrder({

      salesOrderId: formData.salesOrderId,
      ...itemQuery
    })
    if (response.code === 200) {
      itemData.value = response.data.pageData
      itemTotal.value = response.data.totalCount

      // 如果没有数据，显示友好提示
      if (response.data.totalCount === 0) {
        ElMessage.info(response.message || '该销售订单暂无关联物品')
      }
    } else {
      ElMessage.error(response.message || '获取生产物品失败')
    }
  } catch (error) {
    console.error('获取生产物品失败:', error)
    ElMessage.error('获取生产物品失败')
  } finally {
    itemLoading.value = false
  }
}

const searchConsumeItems = async () => {
  itemLoading.value = true
  try {
    const response = await getAllItems(itemQuery)
    if (response.code === 200) {
      itemData.value = response.data.pageData
      itemTotal.value = response.data.totalCount
    } else {
      ElMessage.error(response.message || '获取消耗物品失败')
    }
  } catch (error) {
    console.error('获取消耗物品失败:', error)
    ElMessage.error('获取消耗物品失败')
  } finally {
    itemLoading.value = false
  }
}

const resetItemQuery = () => {
  Object.assign(itemQuery, {
    pageIndex: 1,
    pageSize: 10,
    searchText: '',
    itemType: '',
    itemClassificationId: null,
    inventoryStatus: ''
  })
}

const handleItemSizeChange = (size) => {
  itemQuery.pageSize = size
  itemQuery.pageIndex = 1
  if (productionItemDialogVisible.value) {
    searchProductionItems()
  } else if (consumeItemDialogVisible.value) {
    searchConsumeItems()
  }
}

const handleItemCurrentChange = (page) => {
  itemQuery.pageIndex = page
  if (productionItemDialogVisible.value) {
    searchProductionItems()
  } else if (consumeItemDialogVisible.value) {
    searchConsumeItems()
  }
}

const handleItemSelectionChange = (selection) => {
  selectedItems.value = selection
}

const confirmProductionItems = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择生产物品')
    return
  }

  selectedItems.value.forEach(item => {
    const existingIndex = formData.productionItems.findIndex(p => p.itemId === item.id)
    if (existingIndex === -1) {
      formData.productionItems.push({
        itemId: item.id,
        itemCode: item.itemCode,
        itemName: item.itemName,
        specification: item.specification,
        unit: item.unit,
        itemType: item.itemType,
        itemClassification: '',
        brand: item.brand,
        plannedQuantity: 1,
        remark: ''
      })
    }
  })

  productionItemDialogVisible.value = false
  selectedItems.value = []
}

const confirmConsumeItems = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择消耗物品')
    return
  }

  selectedItems.value.forEach(item => {
    const existingIndex = formData.consumeItems.findIndex(c => c.itemId === item.id)
    if (existingIndex === -1) {
      formData.consumeItems.push({
        itemId: item.id,
        itemCode: item.itemCode,
        itemName: item.itemName,
        specification: item.specification,
        unit: item.unit,
        itemType: item.itemType,
        itemClassification: '',
        brand: item.brand,
        inventory: item.inventory,
        warehouseId: '', // 字符串类型，存储仓库名称
        plannedQuantity: 1,
        number: 1,
        remark: ''
      })
    }
  })

  consumeItemDialogVisible.value = false
  selectedItems.value = []
}

const removeProductionItem = (index) => {
  formData.productionItems.splice(index, 1)
}

const removeConsumeItem = (index) => {
  formData.consumeItems.splice(index, 1)
}

// 附件相关方法
const beforeUpload = (file) => {
  const isValidType = [
    'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/webp',
    'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'text/csv', 'application/pdf',
    'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'text/plain', 'application/zip', 'application/x-rar-compressed'
  ].includes(file.type)

  if (!isValidType) {
    ElMessage.error('不支持的文件类型')
    return false
  }

  const isLt50M = file.size / 1024 / 1024 < 50
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过50MB')
    return false
  }

  return true
}

const handleUploadSuccess = (response, file) => {
  console.log('上传响应:', response)

  // 后端直接返回URL字符串，需要适配这种格式
  let fileUrl = ''
  if (typeof response === 'string') {
    fileUrl = response
  } else if (response.data) {
    fileUrl = response.data
  } else if (response.url) {
    fileUrl = response.url
  }

  if (fileUrl) {
    // 检查是否已经存在相同文件名的附件（更严格的检查）
    const existingAttachments = formData.attachments.filter(att => att.fileName === file.name)
    if (existingAttachments.length > 0) {
      ElMessage.warning(`文件 "${file.name}" 已存在（${existingAttachments.length}个），请勿重复上传`)
      console.warn(`重复文件检查: ${file.name} 已存在 ${existingAttachments.length} 次`)
      console.log('现有附件列表:', formData.attachments.map(att => ({ fileName: att.fileName, id: att.id })))
      return
    }

    const attachment = {
      fileName: file.name,
      fileSize: formatFileSize(file.size),
      uploadDate: new Date().toLocaleString(),
      fileUrl: fileUrl,
      filePath: fileUrl, // 使用URL作为路径
      originalFileName: file.name,
      fileSizeBytes: file.size,
      fileType: file.type,
      fileExtension: file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
    }

    formData.attachments.push(attachment)
    ElMessage.success(`文件 "${file.name}" 上传成功`)
    console.log('附件已添加:', attachment)
  } else {
    ElMessage.error('上传响应格式错误')
    console.error('上传响应格式错误:', response)
  }
}

const handleUploadError = (error, file) => {
  console.error('上传失败:', error)
  ElMessage.error(`文件 "${file.name}" 上传失败: ${error.message || '网络错误'}`)
}

const handleViewAttachment = (attachment) => {
  if (attachment.fileUrl) {
    window.open(attachment.fileUrl, '_blank')
  } else {
    ElMessage.warning('文件链接不可用')
  }
}

// 查看附件方法（用于详情对话框）
const viewAttachment = (attachment) => {
  if (attachment.fileUrl) {
    window.open(attachment.fileUrl, '_blank')
  } else {
    ElMessage.warning('文件链接不可用')
  }
}

// 下载附件方法（用于详情对话框）
const downloadAttachment = async (attachment) => {
  try {
    if (attachment.fileUrl) {
      // 创建一个临时的a标签来下载文件
      const link = document.createElement('a')
      link.href = attachment.fileUrl
      link.download = attachment.fileName || 'download'
      link.target = '_blank'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      ElMessage.success('开始下载文件')
    } else {
      ElMessage.warning('文件链接不可用')
    }
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载文件失败')
  }
}

const handleDeleteAttachment = async (attachment, index) => {
  try {
    if (attachment.id) {
      // 已保存的附件，调用删除API
      const response = await DeleteAttachment({ id: attachment.id })
      if (response.code === 200) {
        formData.attachments.splice(index, 1)
        ElMessage.success('附件删除成功')
      } else {
        ElMessage.error(response.message || '附件删除失败')
      }
    } else {
      // 未保存的附件，直接从列表中移除
      formData.attachments.splice(index, 1)
      ElMessage.success('附件已移除')
    }
  } catch (error) {
    console.error('删除附件失败:', error)
    ElMessage.error('删除附件失败')
  }
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`
}

// 页面初始化
onMounted(() => {
  fetchList()
  fetchSuppliers() // 获取供应商列表
  fetchProjects() // 获取项目列表
  fetchDepartments() // 获取部门列表
  fetchWarehouses() // 获取仓库列表
})
</script>

<style scoped>
.outsourcing-show {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.operation-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.search-form {
  margin-bottom: 20px;
}

.table-header {
  margin-bottom: 10px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-table) {
  margin-bottom: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 物品概要样式 */
.item-summary-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.item-summary-text {
  font-weight: 500;
  color: #303133;
}

.item-summary-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* 附件相关样式 */
.attachment-container {
  width: 100%;
}

.existing-attachments {
  margin-bottom: 20px;
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafbfc;
  margin-bottom: 8px;
  transition: all 0.3s ease;
}

.attachment-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.attachment-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size,
.upload-date {
  font-size: 12px;
  color: #909399;
  margin-right: 15px;
}

.attachment-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.attachment-actions .el-button {
  padding: 4px 8px;
  font-size: 12px;
  transition: all 0.3s ease;
}

.attachment-actions .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.upload-area {
  margin-top: 16px;
}

.upload-area .el-upload {
  width: 100%;
}

.upload-area .el-upload-dragger {
  width: 100%;
  height: 180px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafbfc;
  transition: all 0.3s ease;
}

.upload-area .el-upload-dragger:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.upload-area .el-upload-dragger.is-dragover {
  border-color: #409eff;
  background: #f0f9ff;
}

.upload-area .el-icon--upload {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-area .el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.upload-area .el-upload__text p {
  margin: 0;
  line-height: 1.5;
}

.upload-area .upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}
</style>
